/*
 * @Author Shunzi
 * @Date 2021-07-16 00:20:41
 * @LastEditTime 2021-07-16 12:12:04
 * @LastEditors Shunzi
 * @Description
 * @FilePath /BFFNodeServer/controllers/controller.js
 */
const { join } = require("path");

module.exports = class Controller {
  constructor(router) {
    if (this.constructor === Controller) {
      throw new Error("Controller 不可构造");
    }
    const actions = this.getActionNames(this.__proto__);
    actions.forEach((actionName) => {
      const handler = this[actionName];
      const path = this.getPath(actionName);
      if (router) {
        router.use(join("/", path), handler);
      }
    });
  }
  getPath(path) {
    return Array.from(path.replace("action", ""))
      .map((char) => (/^[A-Z]*$/.test(char) ? "/" + char : char))
      .join("")
      .toLowerCase();
  }

  getActionNames(proto) {
    let names = Object.getOwnPropertyNames(proto).filter((name) =>
      name.startsWith("action")
    );
    if (proto.__proto__) {
      names = names.concat(this.getActionNames(proto.__proto__));
    }
    return names;
  }
};
